package com.prb.tomcat.protocol;

import com.prb.tomcat.exception.InvalidHeaderException;

import java.util.Objects;

public class ProtocolTool {


    private static final String CRLF = "\r\n";


    private static final String KEY_VALUE_SEPARATOR = ":";

    // 解析消息头
    public static RequestHolder parseHeader(String headerStr) {
        if (Objects.isNull(headerStr) || headerStr.isEmpty()) {
            throw new InvalidHeaderException();
        }

        int index = headerStr.indexOf(CRLF);
        if (index == -1) {
            throw new InvalidHeaderException();
        }

        RequestHolder requestHolder = new RequestHolder();
        String firstLine = headerStr.substring(0, index);
        String[] parts = firstLine.split(" ");

        /*
         * 请求头的第一行必须由三部分构成，分别为 METHOD PATH VERSION
         * 比如：
         *     GET /index.html HTTP/1.1
         */
        if (parts.length < 3) {
            throw new InvalidHeaderException();
        }

        requestHolder.setMethod(parts[0]);
        requestHolder.setPath(parts[1]);
        requestHolder.setVersion(parts[2]);

        parts = headerStr.split(CRLF);
        for (String part : parts) {
            index = part.indexOf(KEY_VALUE_SEPARATOR);
            if (index == -1) {
                continue;
            }
            String key = part.substring(0, index);
            if (index == -1 || index + 1 >= part.length()) {
                requestHolder.setHeader(key, "");
                continue;
            }
            String value = part.substring(index + 1);
            requestHolder.setHeader(key, value);
        }

        return requestHolder;
    }

}
